package com.apexsoft.front.common.plugins.loader.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.apexsoft.front.common.plugins.loader.ILoader;
import com.apexsoft.front.common.plugins.loader.annotation.ALoader;

@ALoader(name="Common loader")
public class CommonLoader implements ILoader {
	
	private static final Logger log = LogManager.getRootLogger();

	public void load(ServletContext sc) {
		//加载会话过滤配置
		this.loadSessionConfig(sc);
		log.info("common Loader success");
	}
	
	private void loadSessionConfig(ServletContext context)
	{
		String fileName = Thread.currentThread().getContextClassLoader().getResource("session-filter-config.xml").getPath();
		if (new File(System.getProperty("user.dir") + "/config/session-filter-config.xml").exists()) {
			fileName=System.getProperty("user.dir") + "/config/session-filter-config.xml";
			log.info("load session-filter-config.xml:" + fileName);
		} else {
			log.info("load default session-filter-config.xml:"+fileName);
		}
		InputStream in = null;
		try{
			File configFile = new File(fileName);
			if(!configFile.exists()){
				log.error("配置文件："+fileName+";不存在目录：" +fileName);
			}
			else{
			in = new FileInputStream(configFile);
			SAXReader saxReader = new SAXReader();
			Document doc = saxReader.read(in);
			//读根节点
			Element config = doc.getRootElement();
			Element e_rules = config.element("rules");
			Element e_blacklist = config.element("blacklist");
			Element e_whiteList = config.element("whiteList");
			
			List<String> ruleList = new ArrayList<String>();
			for (Iterator<Element> i = e_rules.elementIterator(); i.hasNext();) 
			{
				Element item = i.next();
				String path = item.attributeValue("path");
				ruleList.add(path);
			}
			List<String> blacklist = new ArrayList<String>();
			for (Iterator<Element> i = e_blacklist.elementIterator(); i.hasNext();) 
			{
				Element item = i.next();
				String path = item.attributeValue("path");
				blacklist.add(path);
			}
			List<String> whiteList = new ArrayList<String>();
			for (Iterator<Element> i = e_whiteList.elementIterator(); i.hasNext();) 
			{
				Element item = i.next();
				String path = item.attributeValue("path");
				whiteList.add(path);
			}
			context.setAttribute("ruleList", ruleList);
			context.setAttribute("blacklist", blacklist);
			context.setAttribute("whiteList", whiteList);
		}
		}
		catch(Exception e){
			log.error(e.getMessage());
			e.printStackTrace();
		}
		finally{
			try{
				if(in!=null)
					in.close();
			}catch(Exception e){
				log.error(e.getMessage());
				e.printStackTrace();
			}
		}
	}

}
